
#include <stdatomic.h>

typedef struct __lock_t { atomic_flag flag; } lock_t;

void init(lock_t *mutex) {
	// 0 -> lock is available, 1 -> held
	// mutex->flag 默认就是 0
}

int  lock(lock_t *mutex, long timeout) 
{
	long start_time = system_current_time();	
	while (atomic_flag_test_and_set(&mutex->flag)) {
		long curr_time = system_current_time();
		if (curr_time - start_time > timeout) {
			// 超时，放弃抢占锁
			return 0;
		}
	}; // spin-wait (do nothing)
	return 1;
}

void unlock(lock_t *mutex) 
{
	atomic_flag_clear(&mutex->flag);
}

